layui.use(['form', 'table', 'layer', 'upload'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        layer = layui.layer,
        upload = layui.upload;;

    loadData(table);

    // 监听搜索操作
    form.on('submit(data-search-btn-sort)', function (data) {
        //执行搜索重载
        table.reload('sort-info-list', {
            page: {curr: 1},//重新从第 1 页开始
            where: data.field
        });

        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(sort-info-list-filter)', function (obj) {
        if (obj.event === 'add') {  // 监听添加操作
            addSort(table);
        }

        if (obj.event === 'edit') {  // 监听添加操作
            init_update_sort(table);
        }

        if (obj.event === 'delete') {  // 监听删除操作
            deleteSort(table);
        }
    });

    //监听表格复选框选择
    table.on('checkbox(sort-info-list-filter)', function (obj) {
        var cacheElement = table.cache['sort-info-list'];
        tableCheckBoxOnly(obj,cacheElement);
    });


    /** 编辑窗开始 */
    uploadEdit(upload);

    //确定按钮点击事件
    $('#fake').click(function () {
        $(this).attr({'disabled': 'disabled'});
        $('#upload_img').click();//单击隐藏的上传按钮
    });

    /*监听提交*/
    form.on('submit(saveSortBtn)', function (data) {
        var formData = new FormData($(".sort-edit-add")[0]);
        var id = $('.id').val();
        var formAuthAjaxs;
        if (id !=='' && id !== null) {
            formAuthAjaxs = formAuthAjax(dl_coder_url.edit_sort[0], formData);
        } else {
            formAuthAjaxs = formAuthAjax(dl_coder_url.add_sort[0], formData);
        }

        if (formAuthAjaxs.code === http_ok) {
            // 掉用父页面的获取列表方法
            parent.layui.table.reload("sort-info-list");

            // 关闭弹出层
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        }
    });
    /** 编辑窗结束 */

});

function deleteSort(table) {
    var selectdata = table.checkStatus('sort-info-list').data;
    if (selectdata.length === 0) {
        lay_tishi("选择一条数据");
        return false;
    }
    if (selectdata.length > 1) {
        lay_tishi("有多条数据");
        return false;
    }
    layer.confirm('确认删除', function (index) {
        const param = {'id':selectdata[0].id};
        var resultData = JSONAuthAjax(dl_coder_url.delete_sort[0], dl_coder_url.delete_sort[1], param);

        if (resultData.code === '200') {
            loadData(table);
            layer.close(index);
        }
    });
}

function addSort(table) {
    layer.open({
        title: '添加分类',
        type: 2,
        maxmin:true,
        area: ['100%', '100%'],
        content: '../../html/blog/sort-edit.html',
        success: function(layers, index){
            layer.full(index);
        },
        min: function(layers, index){
            layer.min(index);
            $("#layui-layer-shade"+index).show();
            return false;
        }
    });

}

function init_update_sort(table) {
    var selectSortdata = table.checkStatus('sort-info-list').data;
    if (selectSortdata === null || selectSortdata.length === 0) {
        lay_tishi("选择一条数据");
        return false;
    }
    if (selectSortdata.length > 1) {
        lay_tishi("有多条数据");
        return false;
    }

    var id = selectSortdata[0].id;
    var sortTitle = selectSortdata[0].sortTitle;
    var sortImgAlert = selectSortdata[0].sortImgAlert;
    var sortValue = selectSortdata[0].sortValue;
    var sortImg = selectSortdata[0].sortImg;
    layer.open({
        title: '修改分类',
        type: 2,
        shade: 0.5,
        maxmin:true,
        resize: true,
        area: ['100%', '100%'],
        content: '../../html/blog/sort-edit.html',
        success: function(layers, index){
            var body = layer.getChildFrame('body', index);
            var findChild = body.find('form');
            findChild.find('.id').val(id);
            findChild.find('.sortImgAlert').val(sortImgAlert);
            findChild.find('.sortTitle').val(sortTitle);
            findChild.find('.sortValue').val(sortValue);
            findChild.find('#fileName').val(sortTitle);
            findChild.find('#colla_img').find('img').remove();
            findChild.find('#colla_img').append('<a href="javascript:void(0);" onclick="openImg();"><img  id="showImg" src="' + sortImg + '" width="200px"></a>');

            layer.full(index);
        },
        min: function(layers, index){
            layer.min(index);
            $("#layui-layer-shade"+index).show();
            return false;
        },
        cancel: function(index, layero){
            layer.close(index);
            return true;
        }
    });
}


function loadData(table, where) {
    table.render({
        elem: '#sort-info-list',
        url: dl_coder_url.sort_page[0],
        toolbar: '#sort-list-toolbar',
        method: dl_coder_url.sort_page[1],
        where: where,
        contentType: 'application/json',
        dataType: 'json',
        request: {
            pageName: 'pageNo', //页码的参数名称，默认：page
            limitName: 'pageSize', //每页数据量的参数名，默认：limit
        },
        headers: headerMap,
        defaultToolbar: ['filter', 'exports', 'print', {
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips'
        }],
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "total": res.data.total, //解析数据长度
                "data": res.data.records, //解析数据列表
                "count": res.data.pages, //解析数据长度
            }
        },
        response: {
            statusName: 'code', //规定数据状态的字段名称，默认：code
            statusCode: 200,//规定成功的状态码，默认：0
            msgName: 'msg', //规定状态信息的字段名称，默认：msg
            countName: 'total', //规定数据总数的字段名称，默认：count
            dataName: 'data', //规定数据列表的字段名称，默认：data
        },
        cols: [[
            {type: "checkbox"},
            {field: 'id',align: 'center', width: 80, title: 'ID', sort: true},
            {field: 'sortTitle',align: 'center', width: 200, title: '分类标题'},
            {field: 'sortImgAlert',align: 'center', width: 200, title: '分类图片注释'},
            {field: 'sortValue',align: 'center',  title: '分类描述'},
            {field: 'sortImg',align: 'center', width: 200, title: '分类图片',templet: "#imgTpl"},
            {field: 'createTime',align: 'center', width: 200, title: '添加时间'},
            {field: 'updateTime',align: 'center', width: 200, title: '修改时间'}
        ]],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 15,
        page: true,
        skin: 'line',
        even: true,
        size: 'sm',
        lineStyle: 'height: 95px;',
        height: 'full-105',
        done: function () {
            setAuthority();
        }
    });
}

//编辑页
//文件上传
function uploadEdit(upload){
    upload.render({
        elem: '#preview_img',
        url: 'upload',
        size: 1024,
        auto: false, //不自动上传
        bindAction: '#upload_img', //上传绑定到隐藏按钮
        choose: function (obj) {
            //预读本地文件
            obj.preview(function (index, file, result) {
                $('#fileName').val(file.name); //展示文件名
                $('#colla_img').find('img').remove();
                $('#colla_img').append('<a href="javascript:void(0);" onclick="openImg();"><img  id="showImg" src="' + result + '" width="200px"></a>');
            })
        },
        done: function (res) {
            $('#credential_hide').val(res.msg); //隐藏输入框赋值
            $('#submitForm').click(); //上传成功后单击隐藏的提交按钮
        },
        error: function (index, upload) {
            layer.msg('上传失败！' + index, {icon: 5});
        }
    });
}

/*查看大图*/
function openImg() {
    var idBar = '#showImg';
    var src = $(idBar)[0].src;
    var width = $(idBar).width();
    var height = $(idBar).height();
    var scaleWH = width / height;
    var bigH = 550;
    var bigW = scaleWH * bigH;
    if (bigW > 1000) {
        bigW = 1000;
        bigH = bigW / scaleWH;
    } // 放大预览图片
    parent.layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        shadeClose: true,
        area: [bigW + 'px', bigH + 'px'], //宽高
        content: '<img width="' + bigW + '" src="' + src + '" />'
    });
}